<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>
<script>

export default {
  name: 'app',
  data() {
    return {
      wsPath: "ws://192.168.31.5:8001/zmfpt-back/websocket/",
      user: {
        userId: '',
        userName: '',
      }
    }
  },
  created() {
  },
  mounted() {
    this.getUserInfo()

  },
  methods: {
    initRtc(){
      this.pc = new RTCPeerConnection()
      this.pc.onaddstream = this.onaddstream
    },
    onaddstream(obj){
      var vid = document.createElement("video");
      document.appendChild(vid);
      vid.srcObject = obj.stream;
    },
    getUserInfo() {
      this.$axios({
        method: "get",
        url: "/getUserInfo"
      }).then(res => {
        if (res.data.code === 200) {
          let user = res.data.data
          sessionStorage.setItem("roleList", user.roleList)
          this.user = {
            userId: user.id,
            userName: user.username,
          }
        }

      })
    },
    initWebSocket() {
      let that = this
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket")
      } else {
        let userId = this.user.userId
        if (userId) {
          console.log("调用了连接websocket ，获取用户id为")
          that.ws = new WebSocket(this.wsPath + userId)
          that.global.setWs(that.ws)
          that.ws.onopen = this.open
          that.ws.onerror = this.error
          that.ws.onclose =function (e){
            // 关闭 websocket
            console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
            console.log("连接已关闭...");
            //断线重新连接
            setTimeout(() => {
              that.initWebSocket();
            }, 2000);
          },
          this.global.ws.onmessage = function (res) {
            let data = JSON.parse(res.data)
            that.$store.commit("common/setContent",data)
          }
        }
      }
    },
    open() {
      console.log("websocket连接成功！")
    },
    error() {
      console.log("websocket连接失败！")
    },
    send(params) {
    },
    close(e) {
      //销毁监听
      this.global.ws.close()
      console.log("websocket已经关闭！")
    },
  },
  destroyed() {
    // 销毁监听
    this.ws.onclose = this.close
  },
  watch:{
    'user.userId'(val){
      if (val!=''){
        this.initWebSocket()
      }
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 0px;
}
</style>
